package com.vcit.quartz.task;

import java.util.List;
import java.util.Calendar;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.vcit.common.core.domain.entity.SysUser;
import com.vcit.system.service.ISysUserService;
import com.vcit.common.utils.DateUtils;
import com.vcit.system.domain.SysBirthdayNotice;
import com.vcit.system.service.ISysBirthdayNoticeService;
import com.vcit.common.core.service.ISmsService;
import com.vcit.common.utils.StringUtils;
import com.vcit.common.exception.ServiceException;

/**
 * 生日提醒定时任务
 * 
 * @author vcit
 */
@Component("birthdayRemindTask")
public class BirthdayRemindTask {
    
    private static final Logger log = LoggerFactory.getLogger(BirthdayRemindTask.class);
    
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private ISysBirthdayNoticeService birthdayNoticeService;

    @Autowired
    private ISmsService smsService;
    
    /**
     * 执行生日提醒任务
     */
    public void checkBirthday() {
        log.info("开始执行生日提醒任务");
        try {
            // 查询今天过生日的用户
            List<SysUser> birthdayUsers = userService.selectUsersByBirthday();
            
            if (birthdayUsers == null || birthdayUsers.isEmpty()) {
                log.info("今天没有用户过生日");
                return;
            }
            
            log.info("找到{}个过生日的用户", birthdayUsers.size());
            
            Calendar now = Calendar.getInstance();
            int currentYear = now.get(Calendar.YEAR);
            
            // 异步处理每个用户的生日提醒
            birthdayUsers.forEach(user -> processUserBirthday(user, currentYear));
            
        } catch (Exception e) {
            log.error("执行生日提醒任务时发生错误", e);
            throw new ServiceException("发送生日短信失败");
        }
    }
    
    /**
     * 异步处理单个用户的生日提醒
     */
    @Async
    protected void processUserBirthday(SysUser user, int currentYear) {
        try {
            // 检查是否已经发送过提醒
            if (hasNoticeBeenSent(user.getUserId(), currentYear)) {
                log.info("用户{}在{}年的生日提醒已发送", user.getNickName(), currentYear);
                return;
            }

            // 创建生日提醒通知记录
            SysBirthdayNotice notice = createBirthdayNotice(user, currentYear);
            
            // 发送各种提醒
            CompletableFuture.allOf(
                sendSmsNotification(user),
                //sendEmailNotification(user),
                sendSystemNotification(user)
            ).exceptionally(throwable -> {
                log.error("发送生日提醒时发生错误 - 用户: {}", user.getNickName(), throwable);
                return null;
            });
            
            log.info("已完成用户{}的生日提醒处理", user.getNickName());
            
        } catch (Exception e) {
            log.error("处理用户{}的生日提醒时发生错误", user.getNickName(), e);
        }
    }
    
    private boolean hasNoticeBeenSent(Long userId, int year) {
        return birthdayNoticeService.checkNoticeExists(userId, year);
    }
    
    private SysBirthdayNotice createBirthdayNotice(SysUser user, int year) {
        SysBirthdayNotice notice = new SysBirthdayNotice();
        notice.setUserId(user.getUserId());
        notice.setStatus("0");
        notice.setNoticeYear(year);
        notice.setCreateTime(DateUtils.getNowDate());
        birthdayNoticeService.insertBirthdayNotice(notice);
        return notice;
    }
    
    @Async
    protected CompletableFuture<Void> sendSmsNotification(SysUser user) {
        return CompletableFuture.runAsync(() -> {
            if (StringUtils.isNotEmpty(user.getPhonenumber())) {
                boolean success = smsService.sendBirthdayWish(user.getPhonenumber(), user.getNickName());
                if (success) {
                    log.info("成功发送生日祝福短信给用户: {}", user.getNickName());
                } else {
                    log.warn("发送生日祝福短信失败 - 用户: {}", user.getNickName());
                }
            }
        });
    }
    
    @Async
    protected CompletableFuture<Void> sendEmailNotification(SysUser user) {
        return CompletableFuture.runAsync(() -> {
            // TODO: 实现邮件发送逻辑
            log.info("TODO: 发送生日祝福邮件给用户: {}", user.getNickName());
        });
    }
    
    @Async
    protected CompletableFuture<Void> sendSystemNotification(SysUser user) {
        return CompletableFuture.runAsync(() -> {
            // TODO: 实现系统消息发送逻辑
            log.info("TODO: 发送系统消息给用户: {}", user.getNickName());
        });
    }
} 